-- || Created by Revelse

MapManager = inherit(Singleton)

function MapManager:constructor()

	print("Loading maps...")
	
	self.m_Spawnpoints = {} -- Saving the spawnpoints
	self.m_Objects     = {}
	self.m_Maplist     = {}
	
	self:getMapList()
end

function MapManager:getSpawnpoints(mapName)
	return self.m_Spawnpoints[mapName]
end

function MapManager:getMaplist() return self.m_Maplist end

function MapManager:getMapsByTag(tag)
	local maps = {}
	for key, value in ipairs(self.m_Maplist) do
		if value:sub(#value-#tag+1,#value) == tag then
			table.insert(maps,value)
		end
	end
	return maps
end

function MapManager:getMapList()
	for resourceKey, resource in ipairs(getResources()) do
		local resourceName = getResourceName(resource)
		if resourceName:find("dm_mta-%a*") then
			if not self.m_Spawnpoints[resourceName] then
				local metaFile = xmlLoadFile((":%s/meta.xml"):format(resourceName))
				if metaFile then
					for fileKey, file in ipairs( xmlNodeGetChildren ( metaFile )) do
						if xmlNodeGetName (file) == "map" then
							local mapPath = (":%s/%s"):format(resourceName,xmlNodeGetAttribute(file,"src"))
							local mapFile = xmlLoadFile(mapPath)
							if mapFile then
								self.m_Spawnpoints[resourceName] = {}
								self.m_Objects[resourceName]     = {}
								table.insert(self.m_Maplist, resourceName)
								
								for mapKey, mapItem in ipairs( xmlNodeGetChildren (mapFile)) do
									if xmlNodeGetName(mapItem,"spawnpoint") then
										table.insert(self.m_Spawnpoints[resourceName],{
										skin = xmlNodeGetAttribute(mapItem,"skin"),
										interior = xmlNodeGetAttribute(mapItem,"interior"),
										team = xmlNodeGetAttribute(mapItem,"team"),
										posX = xmlNodeGetAttribute(mapItem,"posX"),
										posY = xmlNodeGetAttribute(mapItem,"posY"),
										posZ = xmlNodeGetAttribute(mapItem,"posZ"),
										rotX = xmlNodeGetAttribute(mapItem,"rotX"),
										rotY = xmlNodeGetAttribute(mapItem,"rotY"),
										rotZ = xmlNodeGetAttribute(mapItem,"rotZ"),
										})
									end
								end
								
								if #self.m_Spawnpoints[resourceName] == 0 then
									return false
								end
								
								print((" %s - Spawnpoints: %i"):format(resourceName,#self.m_Spawnpoints[resourceName]))
								
								xmlUnloadFile(mapFile)
							end
						end
					end
				end
				xmlUnloadFile(metaFile)
			end
		end
	end
end


